package cn.whpu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class UploadController {

    @RequestMapping("/fileUpload")
    public String fileUpload(String picname, MultipartFile uploadFile ,HttpServletRequest request) throws IOException {

        String fileName="";
        //原始的文件名
        String uploadFileName = uploadFile.getOriginalFilename();
        String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1, uploadFileName.length());

        //把文件加上随机数，防止重复
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //判断是否输入了文件名
        if (!StringUtils.isEmpty(picname)){
            fileName =uuid+"_"+picname+"."+extendName;
        }else{
            fileName=uuid+"_"+uploadFileName;
        }
        System.out.println("要上传的文件："+fileName);
        //获取上传的真实服务器
        String basePath  = request.getSession().getServletContext().getRealPath("/uploads");

        //解决同一文件夹文件过多
        String datePath =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //判断
        File file =new File(basePath+"/"+datePath);
        if (!file.exists()){
            file.mkdir();
        }
        File f =new File(file,fileName);
        uploadFile.transferTo(f);
        System.out.println(f.getAbsolutePath());
        return "success";
    }
}
